package com.basic.framework.filter.params;

import org.apache.commons.io.IOUtils;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;

/****
 * 
 * @author ganxinge
 */
public class HttpServletRequestCopier extends HttpServletRequestWrapper {

	private ServletInputStreamCopier copier;
	private BufferedReader reader;

	public HttpServletRequestCopier(HttpServletRequest request) throws IOException {
		super(request);
		copier = new ServletInputStreamCopier(getRequest().getInputStream());
	}

	@Override
	public ServletInputStream getInputStream() throws IOException {
		return copier;
	}

	@Override
	public BufferedReader getReader() throws IOException {
		if (reader == null) {
			reader = new BufferedReader(new InputStreamReader(copier, getRequest().getCharacterEncoding()));
		}

		return reader;
	}

	public byte[] getCopy() {
		if (copier != null) {
			return copier.getCopy();
		} else {
			return new byte[0];
		}
	}

	private final class ServletInputStreamCopier extends ServletInputStream {

		private ByteArrayInputStream copy;
		private ByteArrayOutputStream outputCopy;

		public ServletInputStreamCopier(InputStream inputStream) throws IOException {
			outputCopy = new ByteArrayOutputStream(1024);
			IOUtils.copy(inputStream, outputCopy);
			this.copy = new ByteArrayInputStream(outputCopy.toByteArray());
		}

		@Override
		public int read() throws IOException {
			return copy.read();
		}

		public byte[] getCopy() {
			return outputCopy.toByteArray();
		}

		@Override
		public boolean isFinished() {
			return false;
		}

		@Override
		public boolean isReady() {
			return false;
		}

		@Override
		public void setReadListener(ReadListener readListener) {
		}

	}
}
